package cn.jbolt.core.enjoy.directive;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.core.util.JBoltDateUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import org.ocpsoft.prettytime.PrettyTime;

import java.util.Date;

/**
 * PrettyTime 自定义指令 时间日期美化
 *
 * @ClassName: PrettyTimeDirective
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2020年11月21日
 */
public class PrettyTimeDirective extends Directive {
	private static final String NULL_RETURN_STR = "刚刚";
	private static final PrettyTime p = new PrettyTime();
	private Expr valueExpr;
	private int paraNum;

	@Override
	public void setExprList(ExprList exprList) {
		this.paraNum = exprList.length();
		if (paraNum == 1) {
			this.valueExpr = exprList.getExpr(0);
		}
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		if (paraNum == 0) {
			write(writer, NULL_RETURN_STR);
		} else {
			outputValue(env, scope, writer);
		}
	}

	/**
	 * 输出处理后的value值
	 *
	 * @param env
	 * @param scope
	 * @param writer
	 */
	private void outputValue(Env env, Scope scope, Writer writer) {
		Object value = this.valueExpr.eval(scope);
		if (value == null || StrKit.isBlank(value.toString())) {
			write(writer, NULL_RETURN_STR);
			return;
		}
		String time = null;
		if (value instanceof String) {
			time = StrUtil.removeAll(p.format(JBoltDateUtil.getDate(value.toString())), " ");
		} else if (value instanceof Date) {
			time = StrUtil.removeAll(p.format((Date) value), " ");
		} else if (value instanceof Long) {
			time = StrUtil.removeAll(p.format(new Date(Long.parseLong(value.toString()))), " ");
		} else {
			time = value.toString();
		}
		write(writer, time);

	}

}
